﻿using UnityEngine;
/// <summary>
/// 基于MonoBehaviour的抽象泛型单例类
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class MonoBehaviourSingleton<T>:MonoBehaviour
    where T : MonoBehaviour
{
    private static T __instance;
    public static T Instance
    {
        get
        {
            if (__instance == null)
            {
                __instance = FindObjectOfType<T>();
                if(__instance == null)
                {
                    GameObject go = new GameObject(typeof(T).ToString());
                    __instance = go.AddComponent<T>();
                }
            }
            return __instance;
        }
    }
    public static void DestroySelf()
    {
        if (__instance != null)
            Destroy(__instance);
    }
    protected virtual void Awake()
    {
        if(__instance == null)
            __instance = this as T;
        else
        {
            Debug.LogWarning("已存在" + typeof(T).ToString() + "单例组件!");
            Destroy(this);
        }
    }
}
